package com.mes.cloud.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> tokens = exchange.getRequest().getHeaders().get("Authorization");
       String token=null;
        if (null!=tokens&&tokens.size()>0){
            token = tokens.get(0);
        }
        String uri=  exchange.getRequest().getURI().getPath();
        if (token == null || token.isEmpty()) {
            if (StringUtils.isNotBlank(uri)&&uri.contains("base/v1/sys_user/login")){
                return chain.filter(exchange);
            }
            log.info( "token is empty..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }


}
